<?php
/**
 * Created by PhpStorm.
 * User: 李京蔚
 * Date: 2018/7/10
 * Time: 13:37
 */

namespace App\Http\Controllers\Users;


use App\Api\Helpers\Api\ApiResponse;
use App\Http\Controllers\Controller;
use App\Models\AccountApi;
use App\Models\Admin;
use App\Models\AdminRole;
use App\Models\AdminRoleAuthority;
use App\Models\AdminRoleRelevancy;
use App\Models\AdminSet;
use App\Models\Answer;
use App\Models\AnswerRecordModel;
use App\Models\AnswerRule;
use App\Models\ApplyRecord;
use App\Models\Article;
use App\Models\ArticleColumn;
use App\Models\ArticleUserRecordModel;
use App\Models\Attendance;
use App\Models\AttendanceAbroadModel;
use App\Models\AttendancesModel;
use App\Models\BeforeMeeting;
use App\Models\BeforeMeetingImg;
use App\Models\BeOnDutiesModel;
use App\Models\CheckProcessing;
use App\Models\CheckProcessingDept;
use App\Models\CheckRecord;
use App\Models\ClassicPush;
use App\Models\ClassicPushTypeModel;
use App\Models\ConferenceRoom;
use App\Models\Date;
use App\Models\Dept;
use App\Models\DeptRelation;
use App\Models\DirectoriesModel;
use App\Models\DirectoriesRecordsModel;
use App\Models\ExchangeModel;
use App\Models\FileQuery;
use App\Models\FileQueryFile;
use App\Models\FileQueryPower;
use App\Models\LeaderTrialModel;
use App\Models\Lecture;
use App\Models\MeetingIssue;
use App\Models\MeetingIssueFile;
use App\Models\MeetingIssueFront;
use App\Models\MeetingIssuesModel;
use App\Models\MeetingIssueStaff;
use App\Models\MeetingPower;
use App\Models\MeetingServer;
use App\Models\MeetingSummary;
use App\Models\MeetingType;
use App\Models\News;
use App\Models\NewsReadModel;
use App\Models\NewsTypeModel;
use App\Models\OtherConfig;
use App\Models\RoomReserve;
use App\Models\Service;
use App\Models\ServiceColumn;
use App\Models\SignAddress;
use App\Models\SignDate;
use App\Models\StaffSignAddress;
use App\Models\Subject;
use App\Models\SubjectMonth;
use App\Models\Summary;
use App\Models\SummaryStaff;
use App\Models\Time;
use App\Models\TimeSet;
use App\Models\Topic;
use App\Models\TopicCommentModel;
use App\Models\User;
use App\Models\UserDownloadModel;
use App\Models\UserRecords;
use App\Models\UserSubjectMonthRecordsModel;
use App\Models\UserSubjectRecordModel;
use App\Models\UserTrialModel;
use App\Models\VacationType;
use App\Models\WebsiteNews;
use EasyWeChat\Factory;
//use function GuzzleHttp\Psr7\str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class ApiController extends BaseController
{
    use ApiResponse;
    protected $user_id = 0;
    protected $token = '';
    protected $user_code = 0;


    public function __construct(Request $request)
    {
        $this->token = $request->header('token');
        if ($this->token) {
            $user = Admin::where('token', $this->token)->first();
            if($user){
                $this->user_id = $user->id;
                $this->user_code = $user->account;
            }

        }
    }


    /**
     * 获取用户信息
     * 通过token获取用户信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserInfo(Request $request){

        $token = $request->header('token');

        if(!$token){

            return response()->json(['status'=>'error',
                'message'=>'未找到token信息',
                'result'=>''], 401);
        }

        $userInfo = Admin::getTokenUser($token);

        if(!$userInfo){

//            return response()->json(['error'=>'用户不存在或token过期'], 400);
            return response()->json(['status'=>'error',
                'message'=>'用户不存在或token过期',
                'result'=>''], 401);
        }

//        return response()->json($userInfo);
        return response()->json(['status'=>'success',
            'message'=>'OK',
            'result'=>$userInfo], 200);


    }


    /**
     * 判断用户是否绑定信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function checkUser(Request $request){

        $uid = $request->get('auth_uid');

        $check = Admin::checkCode($uid);

        if(!$check){

            return $this->json(false,'用户信息获失败');
        }

        $ck = true;

        if(!$check->id_code){

            $ck = false;
        }

        $data = [
            'check'=>$ck,
            'userinfo'=>$check,
        ];

        return $this->json(true,'OK',$data);
    }

    /**
     * 绑定用户信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function bindingUser(Request $request){

        $uid = $request->get('auth_uid');

        $nickname = $request->get('nickname');
        $id_code = $request->get('id_code');

        $input = $request->only('nickname', 'id_code');

        $result = Validator::make($input, [
            'nickname' => 'required',
            'id_code' => 'required|min:18|max:18',
        ], [
            'nickname.required' => '缺少参数！',
            'id_code.required' => '缺少参数！',
            'id_code.min'=>'身份证格式错误',
            'id_code.max'=>'身份证格式错误',
        ]);


        if ($result->fails()) {
            return $this->json(false,$result->errors()->first());
        }

        $user = Admin::checkCode($uid);

        $is_merge = false;

        //是否存在相同信息用户
        $che = Admin::checkIdCode($input['id_code']);

        if(!$che){

            // TODO 提示未查找到此人
            return $this->json(false,'此身份不存在！');
        }

        if($che->id == $uid){

            return $this->json(false,'已绑定');
        }

        if($che->openid){

            return $this->json(false,'该身份已绑定微信！');
        }

        if($che && $che->id != $uid){//合并

            $update = [
                'openid'=>$user->openid,
                'token'=>$user->token,
                'avatar_url'=>$user->avatar_url
            ];

            $in = Admin::addCode($che->id,$update);
            $de = Admin::deletes($uid);
            $user = Admin::checkCode($che->id);

            $is_merge = true;

        }else{


            $update = [

                'nickname'=>$nickname,
                'id_code'=>$id_code,
            ];

            $in = Admin::addCode($uid,$update);
            $user = Admin::checkCode($uid);
        }


        $data = [
            'user'=>$user,
            'is_merge'=>$is_merge
        ];

        if($in){

            return $this->json(true,'绑定成功!',$data);
        }

        return $this->json(false,'绑定失败！');

    }


    /**
     * 首页
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function homepage(Request $request){

        $uid = $request->get('auth_uid');

        //上班-迟到-缺勤
        $att = [
            'work'=>0,
            'late'=>0,
            'lack'=>0,
            'remark'=>'work上班-late迟到-lack缺卡'
        ];
        $work = [];
        $work2 = [];
        $late = [];
        $lack = [];

        $attendances = AttendancesModel::getMonth($uid);

        if($attendances){
            foreach ($attendances as $k=>$v){
                $this_date = date('Y-m-d',strtotime($v->sign_time));
                if(!isset($work[$this_date])){
                    $work[$this_date] = 0;
                }
                switch ($attendances[$k]->status){
                    case 1://迟到
                        $work[$this_date] += 1;

                        if(!isset($work2[$this_date][$attendances[$k]->sign_type])){
                            $work2[$this_date][$attendances[$k]->sign_type] = 0;
                        }
                        $work2[$this_date][$attendances[$k]->sign_type]++;//精确到上下班卡
                        $att['late']++;
                        break;
                    case 0:
                    case 2://早退
                        $work[$this_date] += 1;

                        if(!isset($work2[$this_date][$attendances[$k]->sign_type])){
                            $work2[$this_date][$attendances[$k]->sign_type] = 0;
                        }
                        $work2[$this_date][$attendances[$k]->sign_type]++;//精确到上下班卡
                        break;

                    case 5://缺卡
                        $att['lack']++;
                        break;
                    default:
                        break;
//                    case 3:
//                        break;
//                    case 4:
//                        break;
                }
            }
        }

//        return [$work,$work2,$attendances];

        if($work){
            foreach ($work as $k=>$v){
                if($v >= 2 && count($work2[$k]) >= 2){
                    $att['work']++;
                }
            }
        }

        //常用联系人
        $list = DirectoriesRecordsModel::getRecordsList($uid);

        //事项提醒未读数量
        $where = [
            ['type',1],
            ['status',1],
            ['receiver_id',$uid]
        ];

        //消息
        $news = News::where($where)
            ->get()
            ->toArray();

        $num = count($news);

        //系统消息
        if($news){
            //查询已读状态
            $where = [
                ['uid',$uid]
            ];

            $li = $news;

            $new_ids = array_column($li,'id');

            $read = NewsReadModel::alls($where,$new_ids);
            foreach ($news as $k=>$v){
                $news[$k]['is_read'] = 0;
                if($read){
                    foreach ($read as $kk=>$vv){
                        if($news[$k]['id'] == $read[$kk]['new_id']){
                            $num--;
                            break;
                        }
                    }
                }
            }

        }

        //是否小于0
        if($num < 0){
            $num = 0;
        }

        $data = [
            'att'=>$att,
            'list'=>$list,
            'num'=>$num
        ];

        return $this->json(true,'OK',$data);

    }




}
